import os
import fcntl
import select
import subprocess
import settings
from subprocess import Popen

import util


class Player(object):
	IO_WAIT = 100 # in milliseconds

	def __init__(self):
		
		self.current = ''
		self.process = None
		self.msg = ''



	def play(self, song):
		self.current = song
		self.process = Popen([settings.PLAYER_CMD,  song], stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
		util.non_blocking_stream(self.process.stdout)
		
		r,w,x = select.select([self.process.stdout], [], [self.process.stdout], Player.IO_WAIT)
		if len(r) == 1:
			self.msg = self.process.stdout.read()		
		    return
        
        raise Exception('Nothing to read')

	def is_playing(self):
		if self.process == None:
			return False
		self.process.poll()
		return self.process.returncode == None

	def last_message(self):
		return self.msg


	def stop(self):
		if self.is_playing():
			self.process.terminate()
			self.process = None
